/**
 * 
 */
package org.arpit.masteringextjs.dao.impl;

import java.util.List;

import org.arpit.masteringextjs.dao.DBUtility;
import org.arpit.masteringextjs.dao.MenuDAO;
import org.arpit.masteringextjs.domain.Menu;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

/**
 * @author Arpit.Rathore
 *
 */
public class MenuDAOImpl implements MenuDAO{

	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private static MenuDAO menuDAO;
	
	private MenuDAOImpl() {
		
	}
	
	public static MenuDAO getInstance() {
		if(menuDAO == null) {
			menuDAO = new MenuDAOImpl();
		}
		return menuDAO;
	}

	@Override
	public Menu create(Menu menu) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Menu createdMenu = (Menu) session.merge(menu);
		session.getTransaction().commit();
		session.close();
		return createdMenu;
	}

	@Override
	public Menu findById(Long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Menu.class);
		criteria.add(Restrictions.eq("id", id));
		@SuppressWarnings("unchecked")
		List<Menu> menus = criteria.list();
		
		if(menus.isEmpty()){
			session.getTransaction().commit();
			session.close();
			return null;
		}
		Menu menu = menus.get(0);
		session.getTransaction().commit();
		session.close();
		return menu;
	}

	@Override
	public List<Menu> findParentMenusByGroupId(Long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Menu.class);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.createAlias("groups", "grp");
		criteria.add(Restrictions.eq("grp.id", id));
		criteria.add(Restrictions.isNull("parent"));
		
		@SuppressWarnings("unchecked")
		List<Menu> menus = criteria.list();
		session.getTransaction().commit();
		session.close();
		return menus;
	
	}

	@Override
	public List<Menu> findByParentId(Long parentId) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Menu.class);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.add(Restrictions.eq("parent.id", parentId));
		
		@SuppressWarnings("unchecked")
		List<Menu> menus = criteria.list();
		session.getTransaction().commit();
		session.close();
		return menus;
	
	}
}
